const i18n = require('../i18n/index');
Component({
  data: {
    selected: 0,
    color: "#94a3b8",
    selectedColor: "#0ea5e9",
    list: [{
      pagePath: "/pages/index/index",
      icon: "🏠",
      text: "首页"
    }, {
      pagePath: "/pages/device/device",
      icon: "📱",
      text: "设备"
    }, {
      pagePath: "/pages/profile/profile",
      icon: "👤",
      text: "我的"
    }],
    isTabChanging: false,
    visible: true,
    lastScrollTop: 0
  },
  attached() {
    this.updateSelectedPage();
    this.watchScrollEvent();
    // 多语言：初始化与监听语言变化
    this.updateTexts();
    try {
      if (i18n && typeof i18n.onLangChange === 'function') {
        this._unsubLang = i18n.onLangChange(() => {
          this.updateTexts();
        });
      }
    } catch (e) {}
  },
  detached() {
    if (wx.eventCenter && wx.eventCenter.off) {
      wx.eventCenter.off('tabBar:toggle');
      wx.eventCenter.off('tabBar:show');
      wx.eventCenter.off('tabBar:hide');
      wx.eventCenter.off('page:scroll');
    }
    // 取消语言监听
    try {
      if (this._unsubLang && typeof this._unsubLang === 'function') {
        this._unsubLang();
      }
    } catch (e) {}
  },
  pageLifetimes: {
    show: function() {
      this.updateSelectedPage();
      // 回到前台时同步一次文案
      this.updateTexts();
    }
  },
  methods: {
    updateSelectedPage() {
      const pages = getCurrentPages();
      if (!pages || !pages.length) return;
      const currentPage = pages[pages.length - 1];
      const currentRoute = '/' + currentPage.route;
      const idx = this.data.list.findIndex(item => item.pagePath === currentRoute);
      if (idx !== -1 && idx !== this.data.selected) {
        this.setData({ selected: idx });
      }
    },
    // 多语言：根据当前语言更新 Tab 文案
    updateTexts() {
      try {
        const newList = [{
          pagePath: "/pages/index/index",
          icon: "🏠",
          text: (i18n && typeof i18n.t === 'function') ? i18n.t('tab.home') : '首页'
        }, {
          pagePath: "/pages/device/device",
          icon: "📱",
          text: (i18n && typeof i18n.t === 'function') ? i18n.t('tab.device') : '设备'
        }, {
          pagePath: "/pages/profile/profile",
          icon: "👤",
          text: (i18n && typeof i18n.t === 'function') ? i18n.t('tab.profile') : '我的'
        }];
        this.setData({ list: newList });
      } catch (e) {}
    },
    switchTab(e) {
      if (this.data.isTabChanging) return;
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;
      if (this.data.selected === index) return;
      this.setData({ isTabChanging: true });
      this.setData({ selected: index });
      wx.switchTab({
        url,
        success: () => {
          setTimeout(() => {
            this.setData({ isTabChanging: false });
          }, 100);
        },
        fail: (err) => {
          console.error('切换标签页失败:', err);
          this.setData({ selected: this.data.selected, isTabChanging: false });
        }
      });
    },
    watchScrollEvent() {
      if (!wx.eventCenter) {
        wx.eventCenter = {
          on: (eventName, callback) => {
            if (!wx._eventHandlers) wx._eventHandlers = {};
            if (!wx._eventHandlers[eventName]) wx._eventHandlers[eventName] = [];
            wx._eventHandlers[eventName].push(callback);
          },
          emit: (eventName, ...args) => {
            if (!wx._eventHandlers || !wx._eventHandlers[eventName]) return;
            wx._eventHandlers[eventName].forEach(handler => handler(...args));
          },
          off: (eventName, callback) => {
            if (!wx._eventHandlers || !wx._eventHandlers[eventName]) return;
            if (!callback) {
              wx._eventHandlers[eventName] = [];
            } else {
              wx._eventHandlers[eventName] = wx._eventHandlers[eventName]
                .filter(handler => handler !== callback);
            }
          }
        };
      }
      wx.eventCenter.on('tabBar:toggle', () => {
        this.setData({ visible: !this.data.visible });
      });
      wx.eventCenter.on('tabBar:show', () => {
        this.setData({ visible: true });
      });
      wx.eventCenter.on('tabBar:hide', () => {
        // 保留接口，不默认隐藏
      });
      wx.eventCenter.on('page:scroll', (scrollTop) => {
        // 不自动隐藏
      });
    }
  }
});

